import React from 'react';
import './scss/video.scss';

const videojs = window.videojs;
const $ = window.$||window.jQuery;

export default class VideoPlayer extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            source: '',
            type: '',
        };
        this.playerTypes = {
            mp3:  'audio/mp3',
            mp4:  'video/mp4',
            wmv:  'video/wmv',
            ogv:  'video/ogg',
            webm: 'video/webm',
            flv:  'video/flv',
            m3u8: 'application/x-mpegURL',
            un:   'rtmp/flv'
        };
        // player
        this.player = null;
        this.videoNode = null;
        //
        this.delayReload = null;
    }

    componentDidMount() {
        this.reLoadSource(this.props.source)
    }

    formatTime = (time) => {
        if (!!!time) return;
        let h = parseInt(time/60),
            s = Math.round( time%60 );
        return `${!h?'00':(h<10?`0${h}`:h)}:${!s?'00':(s<10?`0${s}`:s)}`;
    }

    componentWillReceiveProps(nextProps) {
        let isSome = this.props.source === nextProps.source;
        if (!isSome) {
            this.player&&this.player.dispose();
            clearTimeout(this.delayReload);
            this.player = null;
            this.videoNode = null;
            this.delayReload = setTimeout(() => {
                this.reLoadSource(nextProps.source);
            }, 1000);
        } else {

        }
    }

    // destroy player on unmount
    componentWillUnmount() {
        this.player ? this.player.dispose() : 0 ;
    }

    reLoadSource(source) {
        // 重新初始化video-player
        let playerArea = document.querySelector('#engage_video');
        let video = document.createElement('video');
        video.className = 'video-js vjs-default-skin';
        playerArea.appendChild(video);
        this.videoNode = video;

        // 截取后缀格式
        let diotSplit = source.split('.');
        let suffix = diotSplit[diotSplit.length-1];
        let type = this.playerTypes[suffix] ? this.playerTypes[suffix].toLowerCase() : this.playerTypes.un;

        this.setState({
            source: source,
            type: type
        }, () => {
            this.initPlayer();
        });
    }

    initPlayer = () => {
        let thisReact = this;                                       //  react this
        thisReact.player = videojs(this.videoNode, {
            bigPlayButton : false,
            textTrackDisplay : false,
            posterImage: false,
            errorDisplay : false,
            sourceOrder: true,
            loop: true,
            techOrder: ['html5','flash'],
            controlBar : {
                captionsButton : false,
                chaptersButton: false,
                subtitlesButton:false,
                liveDisplay:false,
                playbackRateMenuButton:false
            },
            flash: {
                swf: "./videojs/video-js.swf"
            },
            // poster: "http://vjs.zencdn.net/v/oceans.png",
            sources: [{
                src: thisReact.state.source,
                type: thisReact.state.type
            }],
        }, function onPlayerReady() {
            // dom
            let thisPlayer = this;                                      // player this
            let contomDom = thisReact.createControlBar();               // 创建一个div节点
            let playerDom = thisPlayer.el();
            let controlBar = contomDom.controlBar;
            
            let progressDom = $(controlBar).find('.progress-range');     // 进度条的显示
            let curTimeDom = $(controlBar).find('.current-time');        // 当前时间点
            let totalTimeDom = $(controlBar).find('.total-time');        // 总共时间

            let loopCheckPaused = setInterval(() => {
              let isPaused = !!thisPlayer&&thisPlayer.paused();
              if(isPaused) {
                  thisPlayer.play();
                  thisPlayer.volume(0.1);                                     // 设置初始化音量
                  playerDom.appendChild(contomDom.controlBar);                // 添加进去，css设置好样式就可以了
                  thisPlayer.on('timeupdate', timeChangeCb);
                  bindEvents();
                  appendMusicIcon();
                  clearInterval(loopCheckPaused);
              }
            }, 1000);

            let appendMusicIcon = () => {
              let { source, type } = thisReact.state;
              let andioIcon = contomDom.audioIcon;
              let splitSource = source.split('/');
              let audioName = splitSource[splitSource.length -1];
              andioIcon.querySelector('.audio-name').innerHTML = audioName;
              type !== 'audio/mp3' ? andioIcon.className = 'music-icon-name video-type' : 0;
              playerDom.appendChild(andioIcon);                 // 添加音频图标
            }

            // timeChage 回调
            let timeChangeCb = () => {
                let curTime = thisPlayer.currentTime();
                let durTime = thisPlayer.duration();
                // 获取总共时间 直播流没有时长
                let curPrecent = !durTime || durTime === Infinity ? 100 : Math.round( (curTime/durTime)*100 );
                curTimeDom.html(thisReact.formatTime(curTime));
                !durTime || durTime === Infinity 
                  ? totalTimeDom.val('').hide() 
                  : totalTimeDom.show().html('<i class="line-i">/</i>' + thisReact.formatTime(durTime));
                progressDom.css({'background-size': curPrecent+'%'}).val(curPrecent);
            };

            let bindEvents = () => {
                // 全屏的操作
                $(playerDom).find('.screen-btn').click(function() {
                    let isFullscreen = thisReact.player.isFullscreen();
                    if (!isFullscreen) {
                        thisReact.player.requestFullscreen();
                        $(this).addClass('exit');
                    } else {
                        thisReact.player.exitFullscreen();
                        $(this).removeClass('exit');
                    }
                });
                // 暂停与播放
                $(playerDom).find('.play-pause-btns').click(function() {
                    let isPaused = thisPlayer.paused();
                    if (!isPaused) {
                        thisPlayer.pause();
                        $(this).removeClass('pause').addClass('play');
                    } else {
                        thisPlayer.play();
                        $(this).removeClass('play').addClass('pause');
                    }
                });
                // 滚动条的移动
                $(playerDom).find('.volume-range').on('input', function(e) {
                    thisPlayer.volume(this.value/100);
                    this.style.backgroundSize = this.value + '% 100%';
                });
                // 进度条变化的操作
                progressDom.on('input', function() {
                    thisPlayer.off('timeupdate');
                    thisPlayer.pause();
                    let curPrecent = $(this).val();
                    let curTime = Math.round((curPrecent/100) * thisPlayer.duration());
                    curTimeDom.html(thisReact.formatTime(curTime));
                    $(this).css({'background-size': curPrecent+'%'}).val(curPrecent);
                });
                // 进度条改变的操作
                progressDom.change(function() {
                    let changeVal = $(this).val();
                    let totalTime = thisPlayer.duration();
                    if (!totalTime || totalTime === Infinity) {

                    } else {
                        let resetTime = parseInt((changeVal/100)*totalTime);
                        thisPlayer.currentTime(resetTime);
                    }
                    thisPlayer.play();
                    thisPlayer.on('timeupdate', timeChangeCb);
                });
            }
        });
    }

    createControlBar = () => {
        let controlBar = document.createElement('div');
        let audioIcon = document.createElement('div');
        let noticeHtml = `
          <i class="audio-icon"></i>
          <span class="audio-name"></span>
        `;
        let barHtml = `
          <div class="oparete-btns">
            <span class="play-pause-btns pause"> </span>
            <div class="voice-icon">
              <div class="change-volume-area">
                <span class="range-parent">
                  <input type="range" class="volume-range" min="0" step="1" max="100" value="10" />
                </span>
              </div>
            </div>
          </div>
          <div class="progress">
            <input type="range" class="progress-range" min="0" step="1" max="100" value="0" />
          </div>
          <div class="time-show">
            <span class="current-time"></span>
            <span class="total-time"></span>
          </div>
          <div class="screen-btn"></div>
        `;
        controlBar.className = 'vjs-mycontrol-bar';
        controlBar.innerHTML = barHtml;
        audioIcon.className = 'music-icon-name';
        audioIcon.innerHTML = noticeHtml;
        return { controlBar, audioIcon};
    }

    render = () => <div id="engage_video"> </div>
}